package com.ruoyi.park.service.impl;

import cn.hutool.core.util.IdUtil;
import com.ruoyi.common.core.constant.UserConstants;
import com.ruoyi.common.core.exception.CustomException;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.SecurityUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.park.domain.BuiPark;
import com.ruoyi.park.domain.MaHouseMaterial;
import com.ruoyi.park.domain.MaMaterial;
import com.ruoyi.park.domain.MaWarehouse;
import com.ruoyi.park.domain.vo.MaMaterialExcelVO;
import com.ruoyi.park.mapper.MaHouseMaterialMapper;
import com.ruoyi.park.mapper.MaMaterialMapper;
import com.ruoyi.park.service.IBuiParkService;
import com.ruoyi.park.service.IMaHouseMaterialService;
import com.ruoyi.park.service.IMaMaterialService;
import com.ruoyi.park.service.IMaWarehouseService;
import com.ruoyi.system.api.RemoteBmCodeService;
import com.ruoyi.system.api.domain.RemoteSysBmType;
import com.ruoyi.system.api.enums.SysBmCodeTypeValue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 物资Service业务层处理
 *
 * @author cjie
 * @date 2021-09-16
 */
@Service
public class MaMaterialServiceImpl implements IMaMaterialService {
    @Autowired
    private MaMaterialMapper maMaterialMapper;
    @Autowired
    private MaHouseMaterialMapper houseMaterialMapper;
    @Autowired
    private RemoteBmCodeService remoteBmCodeService;

    @Autowired
    private IMaHouseMaterialService maHouseMaterialService;

    @Autowired
    private IMaWarehouseService maWarehouseService;

    @Autowired
    private IBuiParkService parkService;

    /**
     * 查询物资
     *
     * @param id 物资ID
     * @return 物资
     */
    @Override
    public MaMaterial selectMaMaterialById(String id) {
        List<Map<String, Object>> maps = houseMaterialMapper.selectHouseMaterialQuantityByMaterialId(id);
        MaMaterial maMaterial = maMaterialMapper.selectMaMaterialById(id);
        //maMaterial.setSysBmId(Integer.parseInt(maMaterial.getCategory()));
        if(maps != null){
            maMaterial.setHouseQuantityList(maps);
        }

        return maMaterial;
    }

    /**
     * 查询物资列表
     *
     * @param maMaterial 物资
     * @return 物资
     */
    @Override
    public List<MaMaterial> selectMaMaterialList(MaMaterial maMaterial) {
        List<MaMaterial> materialList = maMaterialMapper.selectMaMaterialList(maMaterial);
        materialList.forEach(material->{
            if(material.getQuantity() != null){
                material.setTotalPrice(material.getUnitPrice().multiply(BigDecimal.valueOf(material.getQuantity())));
            }else{
                material.setQuantity(0d);
                material.setTotalPrice(BigDecimal.valueOf(0));
            }

        });
        return materialList;
    }

    @Override
    public List<MaMaterial> selectHouseMaMaterialList(MaMaterial maMaterial) {
        List<MaMaterial> materialList = maMaterialMapper.selectHouseMaMaterialList(maMaterial);
        materialList.forEach(item->{
            if(item != null){
                if(item.getQuantity() != null && item.getUnitPrice() != null){
                    item.setTotalPrice(item.getUnitPrice().multiply(BigDecimal.valueOf(item.getQuantity())));
                }else{
                    item.setQuantity(0d);
                    item.setTotalPrice(BigDecimal.valueOf(0));
                }
            }
        });
        return materialList;
    }

    /**
     * 新增物资
     *
     * @param maMaterial 物资
     * @return 结果
     */
    @Override
    public AjaxResult insertMaMaterial(MaMaterial maMaterial) {
        //maMaterial.setCategory(String.valueOf(maMaterial.getSysBmId()));
        MaMaterial source = maMaterialMapper.selectMaterialByNameStandardsAndCategory(maMaterial);
        if(source != null){
            return AjaxResult.error("当前物资已在物资清单");
        }else{
            //不存在，插入物料库
            maMaterial.setId(IdUtil.getSnowflake(0, 0).nextIdStr());
            maMaterial.setCreateTime(DateUtils.getNowDate());
            maMaterial.setCreateBy(SecurityUtils.getUsername());
            RemoteSysBmType remoteSysBmTyp = remoteBmCodeService.genGoodsCode(maMaterial.getCategory(), maMaterial.getMaterialName());
            maMaterial.setMaterialNum(remoteSysBmTyp.getNowCode());
            return maMaterialMapper.insertMaMaterial(maMaterial) > 0 ? AjaxResult.success() : AjaxResult.error();
        }
    }

    /**
     * 校验物资编号是否唯一
     * @param maMaterial 物资
     * @return
     */
    public String checkMaterialNumUnique(MaMaterial maMaterial) {
        MaMaterial source = maMaterialMapper.selectMaterialByNum(maMaterial.getMaterialNum());

        if(source != null && !source.getId().equals(maMaterial.getId())){
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 修改物资
     *
     * @param maMaterial 物资
     * @return 结果
     */
    @Override
    public AjaxResult updateMaMaterial(MaMaterial maMaterial) {
        //maMaterial.setCategory(String.valueOf(maMaterial.getSysBmId()));
        MaMaterial source = maMaterialMapper.selectMaterialByNameStandardsAndCategory(maMaterial);
        if(source != null && !source.getId().equals(maMaterial.getId())){
            return AjaxResult.error("当前物资已在物资清单");
        }
        //name 不为空，根据类型，old name ,修改 name

        maMaterial.setUpdateTime(DateUtils.getNowDate());
        maMaterial.setUpdateBy(SecurityUtils.getUsername());

        if(maMaterial.getCategory() !=null){
            RemoteSysBmType remoteSysBmTyp = remoteBmCodeService.genGoodsCode(maMaterial.getCategory(), maMaterial.getMaterialName());
            maMaterial.setMaterialNum(remoteSysBmTyp.getNowCode());
        }

        if(StringUtils.isNotEmpty(maMaterial.getHouseId())){
            MaHouseMaterial maHouseMaterial = houseMaterialMapper.selectMaHouseMaterialByHouseIdAndMaterialId(maMaterial.getHouseId(), maMaterial.getId());
            maHouseMaterial.setQuantity(maMaterial.getQuantity());

            houseMaterialMapper.updateMaHouseMaterial(maHouseMaterial);
        }

        return maMaterialMapper.updateMaMaterial(maMaterial) > 0 ? AjaxResult.success() : AjaxResult.error();
    }

    /**
     * 批量删除物资
     *
     * @param ids 需要删除的物资ID
     * @return 结果
     */
    @Override
    public int deleteMaMaterialByIds(String[] ids) {
        return maMaterialMapper.deleteMaMaterialByIds(ids);
    }

    /**
     * 删除物资信息
     *
     * @param id 物资ID
     * @return 结果
     */
    @Override
    public int deleteMaMaterialById(String id) {
        return maMaterialMapper.deleteMaMaterialById(id);
    }

    /**
     * 删除物资库存
     *
     * @param id 物资ID
     * @return 结果
     */
    @Override
    public int deleteHouseMaMaterialByIds(String[] ids) {
        return maMaterialMapper.deleteHouseMaMaterialByIds(ids);
    }

    /**
     * 查询对应仓库的物资
     *
     * @param maMaterial
     * @return
     */
    @Override
    public List<MaMaterial> selectMaMaterialListByWarehouse(MaMaterial maMaterial) {
        return maMaterialMapper.selectMaterialByWarehouse(maMaterial);
    }

    /**
     * 查询所有物资
     *
     * @param maMaterial 物资
     * @return
     */
    @Override
    public List<MaMaterial> selectAllMaMaterialList(MaMaterial maMaterial) {
        List<MaMaterial> maMaterials = maMaterialMapper.selectAllMaMaterialList(maMaterial);
        maMaterials.forEach(material->{
            material.setQuantity(houseMaterialMapper.selectSumQuantityByMaterialId(material.getId()));
        });

        return  maMaterials;
    }

    @Override
    public String importData(List<MaMaterialExcelVO> buiRoomVOList) {
        if (StringUtils.isNull(buiRoomVOList) || buiRoomVOList.size() == 0) {
            throw new CustomException("导入抄表数据不能为空！");
        }
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        this.insertDataBatch(buiRoomVOList);
        successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + buiRoomVOList.size() + " 条，数据如下：");
        return successMsg.toString();
    }

    @Override
    public List<MaMaterial> getCategory() {
        List<MaMaterial> result = maMaterialMapper.getCategory();
        result = result.stream().filter(o->StringUtils.isNotBlank(o.getCategoryName())).collect(Collectors.toList());
        return result;
    }

    private void insertDataBatch(List<MaMaterialExcelVO> list){
        Map<String,MaWarehouse> maWarehousesMap = maWarehouseService.selectMaWarehouseList(new MaWarehouse()).stream().collect(Collectors.toMap(s->s.getHouseNum(),a->a));
        Map<String,RemoteSysBmType> sysBmTypeMap = new HashMap<>();
        Map<String, BuiPark> parkMap = parkService.selectBuiParkList(new BuiPark()).stream().collect(Collectors.toMap(s->s.getParkNum(),a->a));
        for (MaMaterialExcelVO maMaterialExcelVO : list) {
            //查询物料，物料不存在，插入
            MaMaterial maMaterial = new MaMaterial();
            //查询物料类别
            RemoteSysBmType ss1 = sysBmTypeMap.get(maMaterialExcelVO.getCategory());
            if( ss1== null){
                ss1 = new RemoteSysBmType();
                ss1.setName(maMaterialExcelVO.getCategory());
                ss1.setGenCode(maMaterialExcelVO.getBigCategoryNum()+"-"+maMaterialExcelVO.getCategoryNum());
                List<RemoteSysBmType> sysBmTypeList = remoteBmCodeService.queryGoodsCode(ss1);
                if(sysBmTypeList != null && sysBmTypeList.size()>0){
                    ss1 = sysBmTypeList.get(0);
                    sysBmTypeMap.put(ss1.getName(),ss1);
                }
            }
            maMaterial.setCategory(ss1.getBmId());
            maMaterial.setMaterialName(maMaterialExcelVO.getMaterialName());
            maMaterial.setStandards(maMaterialExcelVO.getStandards());
            MaMaterial source = maMaterialMapper.selectMaterialByNameStandardsAndCategory(maMaterial);
            if(source ==null){
                //不存在，插入物料库
                maMaterial.setId(IdUtil.getSnowflake(0, 0).nextIdStr());
                maMaterial.setUnit(maMaterialExcelVO.getUnit());
                maMaterial.setCreateTime(DateUtils.getNowDate());
                maMaterial.setCreateBy(SecurityUtils.getUsername());
                maMaterial.setUnitPrice(maMaterialExcelVO.getUnitPrice());
                RemoteSysBmType remoteSysBmTyp = remoteBmCodeService.genGoodsCode(maMaterial.getCategory(), maMaterial.getMaterialName());
//                RemoteSysBmType remoteSysBmTyp = remoteBmCodeService.getCodeByGenCode(maMaterialExcelVO.getBigCategoryNum()+"-"+maMaterialExcelVO.getCategoryNum(), SysBmCodeTypeValue.GOODS);
//                if(remoteSysBmTyp !=null){
//                    remoteSysBmTyp = remoteBmCodeService.genGoodsCode(remoteSysBmTyp.getBmId(), maMaterial.getMaterialName());
//                    maMaterial.setCategory(remoteSysBmTyp.getBmId());
//                }
                maMaterial.setMaterialNum(remoteSysBmTyp.getNowCode());
                maMaterialMapper.insertMaMaterial(maMaterial);
            }else {
                maMaterial = source;
            }

            //查询查询库房编号，不存在 插入库房数据；
            MaWarehouse house = maWarehousesMap.get(maMaterialExcelVO.getHouseNum());
            if( house==null){
                house = new MaWarehouse();
                if(StringUtils.isNotEmpty(maMaterialExcelVO.getHouseNum())){
                    house.setHouseNum(maMaterialExcelVO.getHouseNum());
                }else{
                    house.setHouseNum(maMaterialExcelVO.getAddress());
                }
                house.setAddress(maMaterialExcelVO.getAddress());
                house.setParkNum(maMaterialExcelVO.getParkNum());
                if(parkMap.get(maMaterialExcelVO.getParkNum()) != null){
                    house.setParkId(parkMap.get(maMaterialExcelVO.getParkNum()).getId());
                }
                if(StringUtils.isNotEmpty(maMaterialExcelVO.getWarehouse())){
                    house.setWarehouse(maMaterialExcelVO.getWarehouse());
                }else {
                    house.setWarehouse(maMaterialExcelVO.getAddress());
                }
                if(StringUtils.isNotEmpty(house.getHouseNum())|| StringUtils.isNotEmpty(house.getAddress()) || StringUtils.isNotEmpty(house.getWarehouse())){
                    maWarehouseService.insertMaWarehouse(house);
                    maWarehousesMap.put(house.getHouseNum(),house);
                }else {
                    continue;
                }
            }
            //物料库存关系，不存在插入，存在更新；
            MaHouseMaterial mhm = new MaHouseMaterial();
            mhm.setMaterialId(maMaterial.getId());
            if(house != null){
                mhm.setHouseId(house.getId());
            }
            mhm.setQuantity(maMaterialExcelVO.getQuantity());
            List<MaHouseMaterial> list1 = maHouseMaterialService.selectMaHouseMaterialList(mhm);
            if(list1 != null && list1.size() >0){
                mhm.setQuantity(mhm.getQuantity()+ list1.get(0).getQuantity());
                maHouseMaterialService.updateMaHouseMaterial(mhm);
            }else {
                //插入关联关系,数量
                mhm.setQuantity(maMaterialExcelVO.getQuantity());
                maHouseMaterialService.insertMaHouseMaterial(mhm);
            }

        }
    }

}
